<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left">
        <img class="back" @tap="goBack" src="@/static/返回箭头.png"></img>
      </view>
      <!--      <view class="right">-->
      <!--        <text class="icon">↺</text>-->
      <!--        <text class="icon">☆</text>-->
      <!--        <text class="icon">熟</text>-->
      <!--        <text class="icon">⋯</text>-->
      <!--      </view>-->
    </view>

    <!-- 单词展示区 -->
    <view class="word-section">
      <text class="word">{{ currentWord.text }}</text>
      <view class="phonetic" @tap="playPronunciation">
        <view class="radio">
          <text class="region">{{ wordType === 1 ? "英" : "美" }}</text>
          <text class="speaker"><img src="@/static/声音.png" alt="#"></text>
        </view>

        <text class="symbol">/{{ currentWord.phonetic }}/</text>

      </view>
      <text class="tip">先回想词义再选择，想不起来「看答案」</text>
    </view>


    <view class="definitions">
      <view
          class="option-item"
          v-for="(option, index) in options"
          :key="index"
          @tap="selectOption(option)"
      >

        <view class="definition-item">
          <text class="pos">{{ option.pos }}</text>
          <text class="meaning">{{ option.meaning }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button" @tap="toggleAnswer">
      <text>{{ showAnswer ? '下一个' : '看答案' }}</text>
    </view>
  </view>
</template>

<script>
import {api} from "@/utils/request.js"

export default {
  data() {
    return {
      showAnswer: true,
      wordType: 1,
      // currentWord: {
      //   text: 'install',
      //   phonetic: 'ɪnˈstɔːl',
      //   meaning: '安装；把...装到计算机上；任命',
      //   audioUrl: '/static/audio/install.mp3',
      //   phrases: [
      //     {text: 'install software', meaning: '安装软件'},
      //     {text: 'install a new system', meaning: '安装新系统'}
      //   ],
      //   examples: [
      //     {text: 'You need to install the latest version.', meaning: '你需要安装最新版本。'},
      //     {text: 'How do I install this app?', meaning: '我该如何安装这个应用？'}
      //   ]
      // },
      currentWord: {},
      options: [],
      audioContext: null,
      wrongWords: [],
      currentIndex: 0,
      isReviewMode: false,
      startTime: null, // 记录学习开始时间
      learnedWords: [],
    }
  },
  onLoad(options) {

    // 记录学习开始时间
    this.startTime = new Date()
    // 初始化已学习单词数组
    this.learnedWords = []
    uni.setStorageSync('originalWordParams', options)
    this.toggleAnswer()
    return


    // 如果是复习模式
    if (options.mode === 'review') {
      // 获取错误单词列表
      const wrongWordsJson = uni.getStorageSync('wrongWordsToReview')
      if (wrongWordsJson) {
        this.wrongWords = JSON.parse(wrongWordsJson)
        this.currentIndex = 0
        this.isReviewMode = true
        this.loadWrongWord()
      }
    } else {
      // 正常学习模式
      this.getCurrentWord(options.book)
    }
  },
  onUnload() {
    // 移除事件监听，防止内存泄漏
    uni.$off('triggerToggleAnswer')

    // 计算学习时间（毫秒）
    const endTime = new Date()
    const learningTime = endTime - this.startTime

    // 如果有学习记录，发送到后端
    if (this.startTime) {
      this.sendLearningRecord(learningTime)
    }
  },
  methods: {
    async getCurrentWord(type) {
      this.options = []
      const res = await api.getWord(type)
      if (res.code === 200) {
        let correctPos = ""
        let correctMeaning = ""

        const pos = res.result.meaning[0].pos
        correctPos = pos
        correctMeaning = res.result.meaning[0]?.tranCn
        this.options.push({
          "id": res.result.id,
          "pos": correctPos,
          "meaning": correctMeaning,
          "isCorrect": true,
          "correctId": res.result.id,
          "phonetic": res.result.phonetic,
          "synonyms": res.result.synonyms,
          "relWord": res.result.relWord
        })
        this.currentWord = {
          "text": res.result.handWord,
          "meaning": correctMeaning,
          "phrases": res.result.phrases,
          "examples": res.result.sentences,
          "phonetic": res.result.phonetic,
          "synonyms": res.result.synonyms,
          "relWord": res.result.relWord
        }
        res.result.errorWord?.forEach(item => {
          let errorPos = ""
          let errorMeaning = ""
          const pos = item[0]?.pos
          errorPos = pos
          errorMeaning = item[0]?.tranCn
          this.options.push({
            "id": errorMeaning,
            "pos": errorPos,
            "meaning": errorMeaning,
            "isCorrect": false,
            "correctId": res.result.id,
            "phonetic": res.result.phonetic,
            "synonyms": res.result.synonyms,
            "relWord": res.result.relWord
          })
        })


        const shuffled = [...this.options];
        for (let i = shuffled.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        this.options = shuffled;

        // 缓存当前单词数据
        const cacheData = {
          word: this.currentWord,
          options: this.options
        }
      }
    },
    goBack() {
      uni.switchTab({url: '/pages/study/study'})
    },
    playPronunciation() {
      // 创建音频上下文
      const innerAudioContext = uni.createInnerAudioContext();

      // 获取当前单词
      const word = this.currentWord.text;

      // 设置音频源（1为美音，2为英音）
      innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=${this.wordType}`;

      // 监听音频加载完成事件
      innerAudioContext.onCanplay(() => {
        console.log('音频准备就绪');
      });

      // 监听播放错误事件
      innerAudioContext.onError((res) => {
        console.log('播放错误:', res.errMsg);
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        });
      });

      // 监听播放完成事件
      innerAudioContext.onEnded(() => {
        console.log('播放结束');
        // 播放完成后销毁实例
        innerAudioContext.destroy();
      });

      // 开始播放
      innerAudioContext.play();
      this.wordType === 1 ? this.wordType = 2 : this.wordType = 1
    },

    toggleAnswer() {
      // 获取当前路由参数
      this.$nextTick(item => {
        const options = this.$route.query || {}
        // 如果是复习模式，加载错误单词
        if (options.mode === 'review') {
          this.loadWrongWord()
        } else {
          // 正常学习模式，获取新单词
          this.getCurrentWord(this.$route.query.book)
        }
      })
    },
    async selectOption(option) {
      // 如果不是重试模式，才发送请求
      const res = await api.saveWord({
        "isCurrent": option.isCorrect ? 0 : 1,
        "wordId": option.correctId,
        "wordType": this.$route.query.book,
        "model": 0
      })
      if (res.code === 200) {
        console.log("保存成功")
      } else {
        console.log("保存失败")
      }
      // 记录当前学习的单词
      this.learnedWords.push({
        wordId: this.currentWord.text, // 使用单词文本作为ID，实际应用中应使用真实ID
        isCorrect: option.isCorrect
      })

      if (option.isCorrect) {
        // 答对了，跳转到结果页
        const resultData = {
          word: {
            text: this.currentWord.text,
            meaning: this.currentWord.meaning,
            correctAnswer: this.options.find(opt => opt.isCorrect).meaning,
            audioUrl: this.currentWord.audioUrl,
            phrases: this.currentWord.phrases,
            examples: this.currentWord.examples,
            phonetic: this.currentWord.phonetic,
            synonyms: this.currentWord.synonyms,
            relWord: this.currentWord.relWord
          },
          selectedAnswer: option.meaning
        }
        uni.setStorageSync('wordLearningResult', JSON.stringify(resultData))
        // 清除缓存
        uni.navigateTo({
          url: '/pages/word-result/word-result'
        })
      } else {
        // 答错了，跳转到错误页
        const wrongData = {
          word: {
            text: this.currentWord.text,
            phonetic: this.currentWord.phonetic,
            meaning: this.currentWord.meaning,
            correctAnswer: this.options.find(opt => opt.isCorrect).meaning,
            audioUrl: this.currentWord.audioUrl,
            phrases: this.currentWord.phrases,
            examples: this.currentWord.examples,
            synonyms: this.currentWord.synonyms,
            relWord: this.currentWord.relWord
          },
          selectedAnswer: option.meaning
        }
        // 设置重试标记
        uni.setStorageSync('currentWordData', JSON.stringify(wrongData))

        uni.navigateTo({
          url: '/pages/word-wrong/word-wrong'
        })
      }
    },
    loadNextWord() {
      // 这里应该加载下一个单词的逻辑
      // 暂时重置当前单词
      this.currentWord = {
        text: 'fantastic',
        phonetic: 'fænˈtæstɪk',
        meaning: '极好的；极大的；奇异的，荒谬的',
        audioUrl: '/static/audio/fantastic.mp3',
        phrases: [
          {text: 'fantastic story', meaning: '荒诞的故事'}
        ],
        examples: [
          {text: 'The party was fantastic!', meaning: '派对太棒了！'}
        ]
      }
    },
    returnToHome() {
      uni.switchTab({
        url: '/pages/study/study'
      })
    },
    loadWrongWord() {
      // 如果没有错误单词或已经复习完所有错误单词
      if (!this.wrongWords || this.wrongWords.length === 0 || this.currentIndex >= this.wrongWords.length) {
        uni.showToast({
          title: '已完成所有错误单词复习',
          icon: 'none'
        })

        // 清除错误单词缓存
        uni.removeStorageSync('wrongWordsToReview')

        // 返回学习页面
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/study/study'
          })
        }, 1500)
        return
      }

      // 加载当前索引的错误单词
      const wrongWord = this.wrongWords[this.currentIndex]
      this.currentWord = wrongWord

      // 生成选项
      this.generateOptions(wrongWord)

      // 更新进度
      this.currentIndex++
    },
    generateOptions(word) {
      // 清空选项
      this.options = []

      // 添加正确选项
      this.options.push({
        id: word.meaning,
        pos: word.pos || '',
        meaning: word.meaning,
        isCorrect: true
      })

      // 添加错误选项（这里需要根据实际情况生成）
      // 这里简单示例，实际应用中可能需要从API获取或使用预设的错误选项
      const fakeOptions = [
        {meaning: '假选项1', pos: ''},
        {meaning: '假选项2', pos: ''},
        {meaning: '假选项3', pos: ''}
      ]

      // 确保不添加与正确答案相同的选项
      fakeOptions.forEach(option => {
        if (option.meaning !== word.meaning) {
          this.options.push({
            id: option.meaning,
            pos: option.pos,
            meaning: option.meaning,
            isCorrect: false
          })
        }
      })

      // 打乱选项顺序
      const shuffled = [...this.options]
      for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
      }
      this.options = shuffled
    },
    // 发送学习记录到后端
    async sendLearningRecord(learningTime) {
      try {
        // 将学习时间从毫秒转换为秒
        const timeInSeconds = Math.floor(learningTime / 1000)
        console.log(345, timeInSeconds)
        // 准备发送的数据
        const learningData = {
          type: 0,
          learnTime: timeInSeconds, // 学习时间（秒）
        }

        // 发送请求到后端
        const res = await api.recordLearningTime(learningData)

        if (res.code === 200) {
          console.log('学习记录发送成功')
        } else {
          console.error('学习记录发送失败:', res.message)
        }
      } catch (error) {
        console.error('发送学习记录时出错:', error)
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-image: linear-gradient(to bottom, #f8e5d7, #a8e6e2);
  padding: 20px;
  box-sizing: border-box;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 0;

  .left {
    display: flex;
    align-items: center;
    gap: 20rpx;

    img {
      width: 40rpx;
      width: 40rpx;
    }

    .back {
      font-size: 40rpx;
    }

    .progress {
      font-size: 32rpx;
      color: #333;
    }
  }

  .right {
    display: flex;
    gap: 30rpx;

    .icon {
      font-size: 36rpx;
      color: #333;
    }
  }
}

.radio {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(197, 198, 199, 0.5);
  width: 100rpx;
  border-radius: 10px;

  img {
    width: 25rpx;
    height: 25rpx;
  }
}

.word-section {
  margin-top: 10rpx;
  text-align: center;

  .word {
    font-size: 80rpx;
    font-weight: bold;
    color: #333;
  }

  .phonetic {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    margin: 30rpx 0;

    .region {
      font-size: 24rpx;
    }

    .symbol {
      font-size: 32rpx;
      color: #666;
    }

    .speaker {
      font-size: 36rpx;
      margin-left: 10rpx;
    }
  }

  .tip {
    font-size: 28rpx;
    color: #666;
    margin-top: 40rpx;
  }
}

.definitions {
  margin-top: 60rpx;
  padding: 0 20rpx;
  height: 800rpx;

  .definition-item {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .pos {
      color: #666;
      font-size: 28rpx;
      margin-bottom: 10rpx;
      display: block;
    }

    .meaning {
      color: #333;
      font-size: 32rpx;
    }
  }
}

.bottom-button {
  position: fixed;
  bottom: 40rpx;
  left: 40rpx;
  right: 40rpx;
  background: #333;
  color: white;
  text-align: center;
  padding: 25rpx 0;
  border-radius: 10rpx;
  font-size: 32rpx;
}
</style> 